<script setup lang="ts">
import VChart from 'vue-echarts'
import { useChartAutoResize } from '@/mixins/MixinChartAutoResize'
import type { VChartInstance } from '@/types'
import { useChartToolboxDataView } from '@/mixins/MixinChartToolboxDataView'
import { useChartTooltipTheme } from '@/mixins/MixinChartTooltipTheme'

const props = defineProps<{
  data: any[]
  name: string
}>()

const {
  dataView,
} = useChartToolboxDataView(() => ({
  dataViewFirstCellName: '时间',
  optionToContent: (opt: any, g: (d: any[]) => string | HTMLElement) => {
    const source = (opt.dataset[0]?.source || []) as any[]
    let result: any[] = []
    if (source.length > 0) {
      const head = source[0] || []
      const body = source.slice(1) || []
      result = [
        ['时间', ...body.map(v => v[0])],
        ...head.slice(1).map(((v: any, i: number) => {
          return [v, ...body.map(vv => vv.slice(1)[i] ?? '-')]
        })),
      ]
    }
    return g(result)
  },
}))
const tooltipTheme = useChartTooltipTheme()
const chartOption = computed(() => {
  return {
    title: {
      text: props.name,
      top: 10,
      left: 10,
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
      },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
      },
      ...tooltipTheme,
    },
    legend: {
      left: 'center',
      top: 20,
    },
    grid: {
      top: 70,
      left: '2%',
      right: '2%',
      bottom: 20,
      containLabel: true,
    },
    xAxis: {
      type: 'category',
    },
    yAxis: {
      type: 'value',
    },
    series: [
      ...Array(3).fill(1).map(() => ({
        type: 'bar',
        seriesLayoutBy: 'row',
      })),
    ],
    toolbox: {
      show: true,
      top: 10,
      right: 20,
      feature: {
        magicType: {
          type: ['bar', 'line', 'stack'],
        },
        dataView: unref(dataView),
      },
    },
    dataset: {
      source: props.data || [],
    },
  }
})

const chartRef = ref<VChartInstance>()
useChartAutoResize(chartRef, () => ({
  autoresize: true,
}))

const { theme } = storeToRefs(useDesignStore())
watchEffect(() => {
  if (chartRef.value) {
    chartRef.value.setOption({
      theme: theme.value,
    })
  }
})
</script>

<template>
  <VChart
    ref="chartRef" :option="chartOption" :init-options="{
      locale: 'zh',
    }" :theme="theme"
  />
</template>
